package com.biscuit.page.basicservice.utils;

import com.alibaba.fastjson.JSON;
import com.biscuit.page.basicservice.model.enums.BaseResponseEnum;
import com.biscuit.page.basicservice.model.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author mazihao
 * @createTime 2024/3/23 10:41
 */
@Slf4j
public class MD5Util {

    private static final String SALT = "BISCUIT-biscuit-cookie";

    public static String md5(String encrypt) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");

            digest.update((encrypt + SALT).getBytes());

            byte[] bytes = digest.digest();

            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            log.info("MD5Util 加密失败，errorInfo -> {}", JSON.toJSONString(e));
            throw new BaseException(BaseResponseEnum.ERROR_SERVICE.getCode(), "md5 加密失败");
        }
    }

}
